package com.itheima.putige.putige.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.putige.putige.common.CustomException;
import com.itheima.putige.putige.common.R;
import com.itheima.putige.putige.dto.DishDto;
import com.itheima.putige.putige.entity.Category;
import com.itheima.putige.putige.entity.Dish;
import com.itheima.putige.putige.entity.DishFlavor;
import com.itheima.putige.putige.service.CategoryService;
import com.itheima.putige.putige.service.DishFlavorService;
import com.itheima.putige.putige.service.DishService;
import com.itheima.putige.putige.utils.QiniuCloudUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/dish")
@Slf4j
public class DishController {
    @Value("${reggie.path}")
    private String basePath;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private DishFlavorService dishFlavorService;

    @Autowired
    private DishService dishService;

    @Autowired
    private CategoryService categoryService;

    /*
    * 新增菜品
    * */
    @PostMapping
    public R<String> save(@RequestBody DishDto dishDto) {
        try {
            String image = dishDto.getImage();
            if (image.contains("lstp")){
                log.info("将临时文件存入云端,获取新的图片路径");
                image = QiniuCloudUtil.putFile(basePath+image);
                System.out.println("image = " + image+"<================================================");
                //将新的文件路径重新存进对象
                dishDto.setImage(image);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        dishService.saveWithFlavor(dishDto);

        String key = "dish_" + dishDto.getCategoryId() + "_1";
        redisTemplate.delete(key);
        return R.success("新增菜品成功");
    }

    /*
    * 分页查询
    * */
    @GetMapping("/page")
    public R<Page> page(int page,int pageSize,String name){
        Page<Dish> pageInfo = new Page<>(page,pageSize);
        Page<DishDto> dishDtoPage = new Page<>();

        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(name != null,Dish::getName,name);
        queryWrapper.orderByDesc(Dish::getUpdateTime);
        dishService.page(pageInfo,queryWrapper);

        BeanUtils.copyProperties(pageInfo,dishDtoPage,"records");
        List<Dish> records = pageInfo.getRecords();
        List<DishDto> list = records.stream().map((item) ->{
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(item,dishDto);
            Long categoryId = item.getCategoryId();

            Category category = categoryService.getById(categoryId);

            if (category != null){
                String categoryName = category.getName();
                dishDto.setCategoryName(categoryName);
            }

            return dishDto;
        }).collect(Collectors.toList());
        dishDtoPage.setRecords(list);
        return R.success(dishDtoPage);
    }

    @GetMapping("/list")
    public R<List<DishDto>> list(Dish dish) {
        List<DishDto> dishDtoList = null;
        String key = "dish_" + dish.getCategoryId() + "_" + dish.getStatus();
        dishDtoList = (List<DishDto>) redisTemplate.opsForValue().get(key);
        if(dishDtoList != null){
            return R.success(dishDtoList);
        }

        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(dish.getCategoryId() != null, Dish::getCategoryId, dish.getCategoryId());

        queryWrapper.eq(Dish::getStatus, 1);
        queryWrapper.orderByAsc(Dish::getSort).orderByDesc(Dish::getUpdateTime);

        List<Dish> list = dishService.list(queryWrapper);

        dishDtoList = list.stream().map((item) -> {
            DishDto dishDto = new DishDto();
            BeanUtils.copyProperties(item, dishDto);

            Long categoryId = item.getCategoryId();//分类id

            Category category = categoryService.getById(categoryId);
            if (category != null) {
                String categoryName = category.getName();
                dishDto.setCategoryName(categoryName);
            }

            Long dishId = item.getId();
            LambdaQueryWrapper<DishFlavor> lambdaQueryWrapper = new LambdaQueryWrapper<>();
            lambdaQueryWrapper.eq(DishFlavor::getDishId, dishId);

            List<DishFlavor> dishFlavorList = dishFlavorService.list(lambdaQueryWrapper);
            dishDto.setFlavors(dishFlavorList);

            return dishDto;
        }).collect(Collectors.toList());


        redisTemplate.opsForValue().set(key,dishDtoList,60, TimeUnit.MINUTES);
        return R.success(dishDtoList);
    }

    /*
    *根据id查询口味
    * */
    @GetMapping("/{id}")
    public R<DishDto> getById(@PathVariable Long id){
        DishDto dishDto = dishService.getByIdWithFlavor(id);
        return R.success(dishDto);
    }

    /*
    * 修改菜品
    * */
    @PutMapping
    public R<String> update(@RequestBody DishDto dishDto){
        //通过id获取之前的图片信息
        Long id = dishDto.getId();
        String image = dishService.getById(id).getImage();
        try {
            //判断之前的图片是否来自云端,是的话先移除
            if (image.contains("qn.zcscloud.cn")){
                QiniuCloudUtil.delete(image.split("qn.zcscloud.cn/")[1]);
            }
            //加载现在的图片
            String file = QiniuCloudUtil.putFile(basePath + image);
            dishDto.setImage(file);
        } catch (Exception e) {
            e.printStackTrace();
        }
        dishService.updateWithFlavor(dishDto);
        String key = "dish_" + dishDto.getCategoryId() + "_1";
        redisTemplate.delete(key);
        return R.success("修改菜品成功");
    }

    /*
    * 删除菜品
    * */
    @DeleteMapping
    public R<String> delete(@RequestParam List<Long> ids){
        LambdaQueryWrapper<Dish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(Dish::getId,ids);
        queryWrapper.eq(Dish::getStatus,1);
        int count = dishService.count(queryWrapper);
        if (count > 0){
            throw new CustomException("菜品正在销售,不能删除");
        }
        for (Long id : ids) {
            String image = dishService.getById(id).getImage();
            if (image.contains("qn.zcscloud.cn")){
                QiniuCloudUtil.delete(image.split("qn.zcscloud.cn/")[1]);
            }
        }
        dishService.removeByIds(ids);
        return R.success("删除成功");
    }

    /*
    * 修改状态
    * */
    @PostMapping("/status/{status}")
    public R<String> status(@PathVariable int status,@RequestParam List<Long> ids){
        LambdaUpdateWrapper<Dish> queryWrapper = new LambdaUpdateWrapper<>();
        queryWrapper.in(Dish::getId,ids);
        queryWrapper.set(Dish::getStatus,status);
        dishService.update(queryWrapper);
        return R.success("状态修改成功");
    }


}
